<template>
  <div class="subjectlist">
    <basic-container>
      <avue-crud
        ref="crud"
        :option="option"
        :data="data"
        @on-load="onLoad"
        v-model="item"
        @selection-change="selectionChange"
        @refresh-change="onLoad"
        @row-save="rowSave"
        @search-change="searchChange"
        @row-update="rowUpdate"
        @row-del="rowDel"
      >
        <template slot="menuLeft">
          <el-button
            type="danger"
            size="small"
            icon="el-icon-delete"
            plain
            @click="deleteInfo"
            >删 除
          </el-button>
        </template>
        <template slot="menuLeft">
          <el-button
            size="small"
            icon="el-icon-refresh-left"
            plain
            @click="goToCensusManage"
            >返 回
          </el-button>
        </template>
        <template slot="fixedTypeForm">
          <el-select placeholder="请选择问题类型" v-model="item.fixedType">
            <el-option
              v-for="obj1 in fixedTypeList"
              :key="obj1.dictKey"
              :label="obj1.dictValue"
              :value="obj1.dictKey"
            >
            </el-option>
          </el-select>
        </template>
        <template slot="subjecNameForm">
          <el-input v-model="item.subjecName"> </el-input>
        </template>
        <template slot-scope="scope" slot="typeForm">
          <el-select
            placeholder="请选择问题类型"
            style="width: 150px !important"
            @change="typeChange"
            v-model="item.type"
          >
            <el-option
              v-for="obj1 in selecltOption"
              :key="obj1.value"
              :label="obj1.label"
              :value="obj1.value"
            >
            </el-option>
          </el-select>
          <el-select
            placeholder="请选择选项数量"
            @change="countChange"
            v-model="item.questionCount"
            style="width: 150px !important"
            v-if="item.type == 1"
          >
            <el-option
              v-for="obj1 in coutOption"
              :key="obj1.value"
              :label="obj1.label"
              :value="obj1.value"
            >
            </el-option>
          </el-select>
        </template>
        <template slot="answerForm">
          <el-row :span="24" v-show="item.type == 1 || item.type == 2">
            <el-input
              @input="forceUpdate"
              v-for="(items, count) in item.adds"
              :key="count"
              v-model="items.answer"
            >
            </el-input>
          </el-row>
        </template>
        <template slot="opertionInfoForm">
          <el-row>
            <div>
              1.
              题目类型由单选或多选修改为填空或问答时，原作答对应数据将被删除；
            </div>
            <div>2. 题目选项数量减少时，减少部分原作答对应数据将被删除；</div>
          </el-row>
        </template>

        <template slot-scope="{ row, index, size, type }" slot="menu">
          <el-button
            icon="el-icon-edit"
            :size="size"
            :type="type"
            @click.stop="editorInfo(row, index)"
            >编辑</el-button
          >
        </template>
      </avue-crud>
    </basic-container>
  </div>
</template>

<script>
import {
  getProjectsubjectList,
  saveProjectsubject,
  updateProjectsubject,
  deleteProjectsubject,
  getProjectsubjectanswer,
  getDictList,
} from "@/api/census/subject";
export default {
  name: "Projectsubject",
  data() {
    return {
      item: { adds: [] },
      user: {},
      selectionList: [],
      page: {
        pageSize: 10,
      },
      option: {
        excelBtn: false,
        border: true,
        index: true,
        expandLevel: 3,
        editBtn: false,
        selection: true,
        dialogClickModal: false,
        headerAlign: "left",
        align: "left",
        tree: false,
        labelWidth: 100,
        column: [
          {
            width: 130,
            label: "问题类型",
            prop: "fixedType",
            hide: true,
            span: 24,
            rules: [
              {
                required: true,
                trigger: "click",
              },
            ],
            props: {
              label: "dictValue",
              value: "dictKey",
            },
            dicUrl: "/api/blade-system/dict/dictionary?code=fixedType",
          },
          {
            width: 130,
            label: "题号",
            prop: "subjectNo",
            addDisplay: false,
            editDisplay: false,
            rules: [
              {
                required: true,

                message: "请输入题号",
                trigger: "click",
              },
            ],
          },
          {
            label: "题目名称",
            prop: "subjecName",
            searchSpan: 8,
            search: true,
            rules: [
              { required: true, validator: this.validatePass, trigger: "blur" },
            ],
          },
          {
            label: "简称",
            prop: "abbreviation",
            hide: true,
            rules: [
              {
                required: true,
                message: "请输简称",
                trigger: "click",
              },
            ],
          },
          {
            label: "是否可见",
            prop: "status",
            type: "radio",
            rules: [
              {
                required: true,
                message: "请选择是否可见",
                trigger: "click",
              },
            ],
            dicData: [
              {
                label: "否",
                value: 0,
              },
              {
                label: "是",
                value: 1,
              },
            ],
          },
          {
            label: "是否必选",
            prop: "requiredFlag",
            type: "radio",
            rules: [
              {
                required: true,
                message: "请选择是否必选",
                trigger: "click",
              },
            ],
            dicData: [
              {
                label: "可选",
                value: "0",
              },
              {
                label: "必选",
                value: "1",
              },
            ],
          },
          {
            label: "提示",
            hide: true,
            prop: "tipsContent",
          },
          {
            label: "问题类型",
            prop: "type",
            type: "select",
            formslot: true,
            span: 24,
            rules: [
              {
                required: true,
                message: "请选择问题类型",
                trigger: "click",
              },
            ],
            props: {
              label: "label",
              value: "value",
            },
            dicData: [
              {
                label: "单选",
                value: 1,
              },
              {
                label: "填空",
                value: 2,
              },
              {
                label: "问答",
                value: 3,
              },
            ],
          },
          {
            label: "选项内容",
            prop: "answer",
            formslot: true,
            hide: true,
          },
          {
            label: "操作说明",
            prop: "opertionInfo",
            formslot: true,
            hide: true,
            span: 24,
          },
        ],
      },
      data: [],
      coutOption: [],
      selecltOption: [
        {
          label: "单选",
          value: 1,
        },
        {
          label: "填空",
          value: 2,
        },
        {
          label: "问答",
          value: 3,
        },
      ],
      fixedTypeList: [],
      maxSubjectNo: 1,
    };
  },
  computed: {
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.projectSubjectId);
      });
      return ids.join(",");
    },
  },
  created() {
    for (let i = 2; i <= 20; i++) {
      this.coutOption.push({
        label: i,
        value: i,
      });
    }
    this.onLoad();
    this.getSelection();
  },
  methods: {
    getSelection() {
      getDictList(1, 10, { code: "fixedType" }).then((result) => {
        if (result.data.code == "200") {
          let resultData = result.data.data;
          if (resultData.length) {
            this.fixedTypeList = resultData[0].children;
          }
        }
      });
    },
    async onLoad(page = this.page, params = {}) {
      params.projectId = this.$route.query.projectId;
      const {
        data: { data },
      } = await getProjectsubjectList(
        page.currentPage,
        1000,
        Object.assign(params, this.query)
      );
      this.data = data.records;
      console.log(data);
      this.page.total = data.total;
      let subjectNoList = data.records.map((val) => {
        return val.subjectNo * 1;
      });
      let list = subjectNoList.reduce((a, b) => {
        return a > b ? a : b;
      });
      this.maxSubjectNo = list + 1;
    },
    async rowSave(form, done) {
      form.projectId = this.$route.query.projectId;
      form.subjectNo = this.maxSubjectNo;
      console.log(form);
      await saveProjectsubject(form);
      this.onLoad();
      done(form);
    },
    async searchChange(params, done) {
      await this.onLoad(this.page, params);
      done();
    },
    async rowUpdate(form, index, done) {
      form.projectId = this.$route.query.projectId;

      //修改现有数据的subjectAnswerNo参数
      // form.adds.map(item => {
      //   return item.subjectAnswerNo++;
      // });
      await updateProjectsubject(form);
      this.onLoad();

      done(form);
    },
    async rowDel(form) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          return deleteProjectsubject({ ids: form.projectSubjectId });
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
          this.$refs.crud.toggleSelection();
        });
      // await deleteProjectsubject({ ids: form.projectSubjectId });
      // this.onLoad(this.page);
    },
    async deleteInfo() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          return deleteProjectsubject({ ids: this.ids });
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
          this.$refs.crud.toggleSelection();
        });
    },
    countChange(val) {
      let empty = [];
      for (let i = 0; i < val; i++) {
        empty.push({ answer: "", subjectAnswerNo: i });
      }
      this.item.adds = empty;
      this.$forceUpdate();
    },
    async editorInfo(val, index) {
      const {
        data: { data },
      } = await getProjectsubjectanswer(1, 100, {
        projectSubjectId: val.projectSubjectId,
      });
      val.questionCount = data.records.length;
      val.adds = data.records;
      // console.log(val);
      this.$refs.crud.rowEdit(val, index);
    },
    typeChange(val) {
      if (val == 2) this.item.adds = [{ answer: "-", subjectAnswerNo: 1 }];
      else if (val == 1 && this.item.questionCount) {
        this.countChange(this.item.questionCount);
      }
    },
    forceUpdate() {
      this.$forceUpdate();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    goToCensusManage() {
      this.$router.push({ name: "项目管理" });
    },
    getFixedTypeText(value) {
      for (let i = 0; i < this.fixedTypeList.length; i++) {
        let row = this.fixedTypeList[i];
        if (row.value == value) {
          return row.label;
        }
      }
    },
    validatePass(rule, value, callback) {
      if (this.item.fixedType == 0) {
        if (!value) {
          callback(new Error("请输入题目名称!"));
        }
      } else {
        callback();
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.subjectlist {
}
</style>
